import { BaseModel } from '../models/BaseModel.js';
import { dataFiles } from '../config/database.js';

const defaultCourses = [
  {
    id: 1,
    name: '企业级人工智能项目实训一',
    code: 'AI001',
    teacher: '曲凤才',
    teacherId: 2,
    credit: 4,
    hours: 64,
    department: '计算机学院',
    semester: '2023-2024-2',
    status: 'active',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
  {
    id: 2,
    name: '企业级人工智能项目实训二',
    code: 'AI002',
    teacher: '曲凤才',
    teacherId: 2,
    credit: 4,
    hours: 64,
    department: '计算机学院',
    semester: '2023-2024-2',
    status: 'active',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
  {
    id: 3,
    name: 'Python程序设计',
    code: 'PY001',
    teacher: '张老师',
    teacherId: 2,
    credit: 3,
    hours: 48,
    department: '软件学院',
    semester: '2023-2024-2',
    status: 'active',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  }
];

class CourseModel extends BaseModel {
  constructor() {
    super(dataFiles.courses, defaultCourses);
  }

  findByCode(code) {
    return this.findOne({ code });
  }

  findByTeacher(teacherId) {
    const data = this.findAll();
    return data.filter(course => course.teacherId === teacherId);
  }
}

const courseModel = new CourseModel();

export class CourseController {
  // 获取课程列表
  async getCourses(req, res) {
    try {
      console.log('获取课程列表');
      
      const courses = courseModel.findAll();
      
      // 构建响应
      const response = {
        success: true,
        data: courses
      };
      
      res.json(response);
    } catch (error) {
      console.error('获取课程列表失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }

  // 获取课程选项
  async getCourseOptions(req, res) {
    try {
      const courses = courseModel.findAll();
      
      const courseOptions = courses.map(course => ({
        value: course.id,
        label: `${course.name} (${course.code})`
      }));
      
      res.json({
        success: true,
        data: courseOptions
      });
    } catch (error) {
      console.error('获取课程选项失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }

  // 创建课程
  async createCourse(req, res) {
    try {
      const { 
        name, 
        code, 
        teacher, 
        students, 
        duration, 
        status, 
        credit, 
        hours, 
        teacherId,
        department,
        semester
      } = req.body;
      
      console.log('创建课程:', { name, code });
      
      if (!name || !code) {
        return res.status(400).json({ 
          success: false,
          error: '课程名称和代码为必填字段' 
        });
      }

      // 检查课程代码是否已存在
      const existingCourse = courseModel.findByCode(code);
      if (existingCourse) {
        return res.status(400).json({ 
          success: false,
          error: '课程代码已存在' 
        });
      }

      const newCourse = {
        name,
        code,
        teacher: teacher || '',
        students: parseInt(students) || 0,
        duration: duration || '',
        status: status || 'upcoming',
        credit: parseInt(credit) || 0,
        hours: parseInt(hours) || 0,
        teacherId: teacherId || null,
        department: department || '',
        semester: semester || '',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };

      const createdCourse = courseModel.create(newCourse);
      
      if (createdCourse) {
        console.log('创建课程成功:', createdCourse);
        res.status(201).json({
          success: true,
          data: createdCourse
        });
      } else {
        res.status(500).json({ 
          success: false,
          error: '保存失败' 
        });
      }
    } catch (error) {
      console.error('创建课程失败:', error);
      res.status(500).json({ 
        success: false,
        error: '创建失败' 
      });
    }
  }

  // 更新课程
  async updateCourse(req, res) {
    try {
      const { id } = req.params;
      const { 
        name, 
        code, 
        teacher, 
        students, 
        duration, 
        status, 
        credit, 
        hours, 
        teacherId,
        department,
        semester
      } = req.body;
      
      console.log('更新课程:', id, { name, code });

      // 检查课程代码是否被其他课程使用
      if (code) {
        const existingCourse = courseModel.findByCode(code);
        if (existingCourse && existingCourse.id !== parseInt(id)) {
          return res.status(400).json({ 
            success: false,
            error: '课程代码已被其他课程使用' 
          });
        }
      }

      const updatedData = {
        name: name || undefined,
        code: code || undefined,
        teacher: teacher || undefined,
        students: students !== undefined ? parseInt(students) : undefined,
        duration: duration || undefined,
        status: status || undefined,
        credit: credit !== undefined ? parseInt(credit) : undefined,
        hours: hours !== undefined ? parseInt(hours) : undefined,
        teacherId: teacherId !== undefined ? teacherId : undefined,
        department: department || undefined,
        semester: semester || undefined,
        updatedAt: new Date().toISOString()
      };

      // 过滤掉undefined值
      const filteredData = Object.fromEntries(
        Object.entries(updatedData).filter(([_, value]) => value !== undefined)
      );

      const updatedCourse = courseModel.update(id, filteredData);

      if (updatedCourse) {
        console.log('更新课程成功:', updatedCourse);
        res.json({
          success: true,
          data: updatedCourse
        });
      } else {
        res.status(404).json({ 
          success: false,
          error: '课程不存在' 
        });
      }
    } catch (error) {
      console.error('更新课程失败:', error);
      res.status(500).json({ 
        success: false,
        error: '更新失败' 
      });
    }
  }

  // 删除课程
  async deleteCourse(req, res) {
    try {
      const { id } = req.params;
      console.log('删除课程:', id);
      
      const success = courseModel.delete(id);
      
      if (success) {
        console.log('删除课程成功');
        res.json({ 
          success: true,
          message: '删除成功' 
        });
      } else {
        res.status(404).json({ 
          success: false,
          error: '课程不存在' 
        });
      }
    } catch (error) {
      console.error('删除课程失败:', error);
      res.status(500).json({ 
        success: false,
        error: '删除失败' 
      });
    }
  }
}